package com.ly.heart.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ly.common.PageParam;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.SysDept;
import com.ly.common.core.domain.entity.SysUser;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.*;
import com.ly.heart.domain.*;
import com.ly.heart.domain.dto.*;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.heart.domain.vo.KingProcureRefundVo;
import com.ly.heart.domain.vo.OrderSumResult;
import com.ly.heart.domain.vo.select.KingProcureRefundSelectVo;
import com.ly.heart.domain.vo.select.query.KingProcureRefundSelectQueryDto;
import com.ly.heart.mapper.KingProcureRefundMapper;
import com.ly.heart.service.*;
import com.ly.heart.util.ChineseToPinyin;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.system.service.ISysDeptService;
import com.ly.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 金蝶-采购退料单Service业务层处理
 *
 * @author cxl
 * @date 2024-07-16
 */
@Service
public class KingProcureRefundServiceImpl extends ServiceImpl<KingProcureRefundMapper,KingProcureRefundEntity> implements IKingProcureRefundService {

    @Resource
    private KingProcureRefundMapper kingProcureRefundMapper;
    @Resource
    private ISysDeptService sysDeptService;
    @Resource
    private IKingInventoryService kingInventoryService;
    @Resource
    private IKingInventoryMaterialService kingInventoryMaterialService;
    @Resource
    private IKingInventoryMaterialDetailService kingInventoryMaterialDetailService;
    @Resource
    private IKingProcureRefundMaterialService kingProcureRefundMaterialService;
    @Resource
    private IKingProcureRefundMaterialDetailService kingProcureRefundMaterialDetailService;
    @Resource
    private IKingProcureRefundMaterialDetailSerialService kingProcureRefundMaterialDetailSerialService;
    @Resource
    private IActModelService actModelService;
    @Resource
    private IActTaskCommentService actTaskCommentService;
    @Resource
    private IKingInvoicePayableDetailService kingInvoicePayableDetailService;
    @Resource
    private IKingRealInventoryService kingRealInventoryService;
    @Resource
    private IKingCheckMaterialUseDecisionService checkMaterialUseDecisionService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private IKingBaseBusinessGroupDetailService kingBaseBusinessGroupDetailService;
    @Resource
    private ISupplierContactsService supplierContactsService;
    @Resource
    private IKingBaseContactsService baseContactsService;
    @Resource
    private IKingBaseSettlementTypeService kingBaseSettlementTypeService;
    @Resource
    private IKingBaseCurrencyService kingBaseCurrencyService;
    @Resource
    private IKingBaseReceiptPayConditionService kingBaseReceiptPayConditionService;
    @Resource
    private IKingBaseMeteringUnitService meteringUnitService;
    @Resource
    private ISupplierService supplierService;
    @Resource
    private IKingPurchasePriceService kingPurchasePriceService;
    @Resource
    private IKingBaseExchangeRateTypeService kingBaseExchangeRateTypeService;
    @Resource
    private IKingBaseInventoryStatusService kingBaseInventoryStatusService;
    @Resource
    private IWarehouseService warehouseService;



    @Override
    public AjaxResult getKingProcureRefundPageListByMaterial(KingProcureRefundQueryDto queryDto) {
        List<KingProcureRefundVo> list = kingProcureRefundMaterialService.getKingProcureRefundList(queryDto);
        list.forEach(procureRefundVo -> {
            ActTaskCommentEntity actTaskCommentEntity = actTaskCommentService.queryLastComment(procureRefundVo.getInstanceId());
            if ( actTaskCommentEntity != null ) {
                procureRefundVo.setApprovedUser ( actTaskCommentEntity.getApprovedUser () );
                procureRefundVo.setApprovedRemark ( actTaskCommentEntity.getRemark () );
            }
            ActCurrentTaskVo currentTaskVo = actModelService.getCurrentTaskByInstanceId(procureRefundVo.getInstanceId());
            Optional.ofNullable(currentTaskVo).ifPresent(procureRefundVo::setCurrentTask);

            KingProcureRefundMaterialQueryDto materialQueryDto = new KingProcureRefundMaterialQueryDto();
            materialQueryDto.setProcureRefundId(procureRefundVo.getId());
            materialQueryDto.setMaterialDetailId(procureRefundVo.getMaterialDetailId());

            /**当月总成本【等于金额】**/
            procureRefundVo.setCurrentMonthTotalCost(procureRefundVo.getAmountMoney());

            /**当月单位成本【等于当月总成本/退料数量】**/
            String currentMonthUnitCost = CommonUtil.divisionStr(procureRefundVo.getAmountMoney(), procureRefundVo.getRefundNum(), 2);
            procureRefundVo.setCurrentMonthUnitCost(currentMonthUnitCost);

            /**当月总成本(本位币)【等于金额(本位币)】**/
            procureRefundVo.setCurrentMonthTotalCostBase(procureRefundVo.getAmountMoneyBase());

            /**当月单位成本(本位币)【等于金额(本位币)/退料数量】**/
            String currentMonthUnitCostBase = CommonUtil.divisionStr(procureRefundVo.getAmountMoneyBase(), procureRefundVo.getRefundNum(), 2);
            procureRefundVo.setCurrentMonthUnitCostBase(currentMonthUnitCostBase);

            /**累计应付统计(应付单源单为退料单,且审核已通过)**/
            OrderSumResult totalPayableResult = kingInvoicePayableDetailService.getNumAndTotalTaxPriceByProcureRefund(materialQueryDto);
            //累计应付数量(已审核)
            procureRefundVo.setTotalPayableNum(totalPayableResult.getTotalNum());
            //累计应付价税合计
            procureRefundVo.setTotalPayableTotalPriceTax(totalPayableResult.getTotalAmount());

            /**剩余应付统计**/
            //剩余应付数量(已审核状态，退料数量+累计应付数量)
            String surplusPayableNum = CommonUtil.sumStr(procureRefundVo.getRefundNum(), totalPayableResult.getTotalNum(), 2);
            procureRefundVo.setSurplusPayableNum(surplusPayableNum);
            //剩余应付价税合计(价税合计+累计应付价税合计)
            String surplusPayableTotalPriceTax = CommonUtil.sumStr(procureRefundVo.getTotalTaxPrice(), totalPayableResult.getTotalAmount(), 2);
            procureRefundVo.setSurplusPayableTotalPriceTax(surplusPayableTotalPriceTax);

            /**累计应付/剩余应付统计**/
            //累计应付单对应源单金额(应付单源单类型为采购入库单)
            KingInventoryMaterialQueryDto inventoryMaterialDto = new KingInventoryMaterialQueryDto();
            inventoryMaterialDto.setInventoryId(procureRefundVo.getSourceId());
            inventoryMaterialDto.setMaterialDetailId(procureRefundVo.getMaterialDetailId());
            OrderSumResult parentProcureRefundResult = kingInvoicePayableDetailService.getParentAmountMoneyAndTotalTaxPriceByProcureRefund(inventoryMaterialDto);
            //此处借用totalNum字段，赋值源单金额
            procureRefundVo.setTotalPayableSourceDocAmount(parentProcureRefundResult.getTotalNum());
            //累计应付单对应源单价税合计
            procureRefundVo.setTotalPayableSourceDocTotalPriceTax(parentProcureRefundResult.getTotalAmount());
            //剩余应付单对应源单金额(金额-累计应付单对应源单金额)
            String surplusPayableSourceDocAmount = CommonUtil.subStr(procureRefundVo.getAmountMoney(), parentProcureRefundResult.getTotalNum(), 2);
            procureRefundVo.setSurplusPayableSourceDocAmount(surplusPayableSourceDocAmount);
            //剩余应付单对应源单价税合计(价税合计-累计应付单对应源单价税合计)
            String surplusPayableSourceDocTotalPriceTax = CommonUtil.subStr(procureRefundVo.getTotalTaxPrice(), parentProcureRefundResult.getTotalAmount(), 2);
            procureRefundVo.setSurplusPayableSourceDocTotalPriceTax(surplusPayableSourceDocTotalPriceTax);
        });
        Page<KingProcureRefundVo> page = new Page<>(queryDto.getPage(), queryDto.getLimit());
        return AjaxResult.success ( ReturnPage.getReturnPage ( page, list ) );
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult draft(KingProcureRefundEntity kingProcureRefund){
        if(StringUtils.isEmpty(kingProcureRefund.getId())){
            String procureRefundId = SnowflakeIdWorker.getInstance().nextStringId();
            String userId = SecurityUtils.getLoginUser().getUser().getUserId();
            Date nowDate = DateUtils.getNowDate();
            //设置采购退料单基本信息
            kingProcureRefund.setId(procureRefundId).setCreateName(userId).setCreateTime(nowDate).setIsSend(KingConstUtil.KING_DATA_IS_SEND_NO);
            //生成采购退料单单号
            if(StringUtils.isEmpty(kingProcureRefund.getDocCode())){
                String companyId = CurrentUserUtil.getCompanyId();
                SysDept sysDept = sysDeptService.getById(companyId);
                int count = kingProcureRefundMapper.queryCount();
                String countStr = String.format("%06d", count);
                String firstLetter = ChineseToPinyin.getFirstLetter(sysDept.getDeptName());
                String docCode = firstLetter.concat("_CGTL_").concat(countStr);
                kingProcureRefund.setDocCode(docCode);
            }
            List<KingProcureRefundMaterialEntity> materialLists = kingProcureRefund.getMaterialLists();
            //保存物料明细以及物料分录信息
            if(!CollectionUtils.isEmpty(materialLists)){
                saveMaterialAndDetail(kingProcureRefund,materialLists);
            }
            //计算合计
            double taxAmount = materialLists.stream ().mapToDouble ( detail -> Double.parseDouble ( StringUtils.isBlank ( detail.getTaxAmount () ) ? "0" : detail.getTaxAmount () ) ).sum ();
            double moneyAmount = materialLists.stream ().mapToDouble ( detail -> Double.parseDouble ( StringUtils.isBlank ( detail.getAmountMoney () ) ? "0" : detail.getAmountMoney () ) ).sum ();
            double totalTaxPrice = materialLists.stream ().mapToDouble ( detail -> Double.parseDouble ( StringUtils.isBlank ( detail.getTotalTaxPrice () ) ? "0" : detail.getTotalTaxPrice () ) ).sum ();
            double taxAmountBase = materialLists.stream().mapToDouble(detail -> Double.parseDouble(StringUtils.isBlank(detail.getTaxAmountBase()) ? "0" : detail.getTaxAmountBase())).sum();
            double totalTaxPriceBase = materialLists.stream().mapToDouble(detail -> Double.parseDouble(StringUtils.isBlank(detail.getTotalTaxPriceBase()) ? "0" : detail.getTotalTaxPriceBase())).sum();
            double amountMoneyBase = materialLists.stream().mapToDouble(detail -> Double.parseDouble(StringUtils.isBlank(detail.getAmountMoneyBase()) ? "0" : detail.getAmountMoneyBase())).sum();
            kingProcureRefund.setTaxAmount ( String.valueOf ( taxAmount ) );
            kingProcureRefund.setMoneyAmount ( String.valueOf ( moneyAmount ) );
            kingProcureRefund.setTotalPriceTax ( String.valueOf ( totalTaxPrice ) );
            kingProcureRefund.setTaxAmountBase(String.valueOf(taxAmountBase));
            kingProcureRefund.setTotalPriceTaxBase(String.valueOf(totalTaxPriceBase));
            kingProcureRefund.setMoneyAmountBase(String.valueOf(amountMoneyBase));
            //设置货主类型以及货主
            kingProcureRefund.setCargoOwnerType("BD_OwnerOrg");
            kingProcureRefund.setCargoOwner("100");
            //流程状态：暂存
            kingProcureRefund.setState(ConstUtil.STATE_IN_DRAFT);
            boolean save = this.save(kingProcureRefund);
            if(save){
                return AjaxResult.success("暂存采购退料单成功！",kingProcureRefund.getId());
            }
            return AjaxResult.error("暂存采购退料单失败！");
        }else{
            return update(kingProcureRefund);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult submit(KingProcureRefundEntity kingProcureRefund) {
        if ( StringUtils.isBlank ( kingProcureRefund.getId () ) ) {
            return AjaxResult.error ("请先暂存该单据！");
        }
        //检查物料信息
        if(CollectionUtils.isEmpty(kingProcureRefund.getMaterialLists())){
            return AjaxResult.error("物料信息不能为空！");
        }
        List<KingProcureRefundMaterialEntity> materialLists = kingProcureRefund.getMaterialLists();
        materialLists.forEach(procureRefundMaterial -> {
            if(StringUtils.isNotEmpty(procureRefundMaterial.getSourceType())){
                //采购订单下推
                if(procureRefundMaterial.getSourceType().equals(ConstUtil.PROCURE_REFUND_SOURCE_TYPE_INVENTORY)){
                    List<String> inventoryIdList = materialLists.stream().filter(Objects::nonNull).distinct().map(KingProcureRefundMaterialEntity::getSourceInventoryId).collect(Collectors.toList());
                    List<KingInventoryEntity> inventoryList = kingInventoryService.list(new QueryWrapper<KingInventoryEntity>().in("id", inventoryIdList));
                    //判断采购入库单的供应商是否一致
                    List<String> supplierIdList = inventoryList.stream().filter(Objects::nonNull).distinct().map(KingInventoryEntity::getSupplierId).collect(Collectors.toList());
                    if(!supplierIdList.isEmpty() && supplierIdList.size() >= 2){
                        throw new CustomException("所选单据供应商不一致，无法操作！");
                    }
                    //判断采购组织是否不同
                    List<String> purchaseOrgList = inventoryList.stream().filter(Objects::nonNull).distinct().map(KingInventoryEntity::getPurchaseOrg).collect(Collectors.toList());
                    if(!purchaseOrgList.isEmpty() && purchaseOrgList.size() >= 2){
                        throw new CustomException("所选单据采购组织不一致，无法操作！");
                    }
                    //判断币别是否不同
                    List<String> settlementCurrencyList = inventoryList.stream().filter(Objects::nonNull).distinct().map(KingInventoryEntity::getSettlementCurrency).collect(Collectors.toList());
                    if(!settlementCurrencyList.isEmpty() && settlementCurrencyList.size() >= 2){
                        throw new CustomException("所选单据结算币别不一致，无法操作！");
                    }
                    //检查出库数量是否匹配
                    checkMaterialNumByInventory(procureRefundMaterial);
                }
                //收料通知单下推
                if(procureRefundMaterial.getSourceType().equals(ConstUtil.PROCURE_REFUND_SOURCE_TYPE_RECEIVE_NOTICE)){
                    checkMaterialNumByReceiveNotice(procureRefundMaterial);
                }
            }
        });
        //先删除暂存时保存的物料明细数据
        removeMaterialAndDetail(kingProcureRefund.getId());
        //保存物料明细数据
        saveMaterialAndDetail(kingProcureRefund,materialLists);
        //计算合计
        double taxAmount = materialLists.stream ().mapToDouble ( detail -> Double.parseDouble ( StringUtils.isBlank ( detail.getTaxAmount () ) ? "0" : detail.getTaxAmount () ) ).sum ();
        double moneyAmount = materialLists.stream ().mapToDouble ( detail -> Double.parseDouble ( StringUtils.isBlank ( detail.getAmountMoney () ) ? "0" : detail.getAmountMoney () ) ).sum ();
        double totalTaxPrice = materialLists.stream ().mapToDouble ( detail -> Double.parseDouble ( StringUtils.isBlank ( detail.getTotalTaxPrice () ) ? "0" : detail.getTotalTaxPrice () ) ).sum ();
        double taxAmountBase = materialLists.stream().mapToDouble(detail -> Double.parseDouble(StringUtils.isBlank(detail.getTaxAmountBase()) ? "0" : detail.getTaxAmountBase())).sum();
        double totalTaxPriceBase = materialLists.stream().mapToDouble(detail -> Double.parseDouble(StringUtils.isBlank(detail.getTotalTaxPriceBase()) ? "0" : detail.getTotalTaxPriceBase())).sum();
        double amountMoneyBase = materialLists.stream().mapToDouble(detail -> Double.parseDouble(StringUtils.isBlank(detail.getAmountMoneyBase()) ? "0" : detail.getAmountMoneyBase())).sum();
        kingProcureRefund.setTaxAmount ( String.valueOf ( taxAmount ) );
        kingProcureRefund.setMoneyAmount ( String.valueOf ( moneyAmount ) );
        kingProcureRefund.setTotalPriceTax ( String.valueOf ( totalTaxPrice ) );
        kingProcureRefund.setTaxAmountBase(String.valueOf(taxAmountBase));
        kingProcureRefund.setTotalPriceTaxBase(String.valueOf(totalTaxPriceBase));
        kingProcureRefund.setMoneyAmountBase(String.valueOf(amountMoneyBase));
        //启动审批流程
        StartProcessDto startDto = new StartProcessDto().setBusinessId(kingProcureRefund.getId()).setBusinessType(kingProcureRefund.getBusinessType()).setModelId(kingProcureRefund.getModelId());
        startDto.setBusinessName("采购退料单_".concat(kingProcureRefund.getDocCode()));
        String instanceId = actModelService.startProcess(startDto);
        kingProcureRefund.setState(ConstUtil.STATE_IN_PROCESS).setInstanceId(instanceId).setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId()).setUpdateTime(DateUtils.getNowDate());
        boolean updated = this.updateById(kingProcureRefund);
        if ( !updated ) {
            return AjaxResult.error( "提交采购退料单失败!" );
        }
        return AjaxResult.success ( "提交采购退料单成功!" );
    }

    @Override
    public AjaxResult update(KingProcureRefundEntity kingProcureRefund) {
        if(StringUtils.isEmpty(kingProcureRefund.getId())){
            return AjaxResult.error("采购退料单id不能为空！");
        }
        //先删除暂存时保存的物料明细数据
        removeMaterialAndDetail(kingProcureRefund.getId());
        List<KingProcureRefundMaterialEntity> materialLists = kingProcureRefund.getMaterialLists();
        if(!CollectionUtils.isEmpty(materialLists)){
            //保存物料明细数据
            saveMaterialAndDetail(kingProcureRefund,materialLists);
        }
        //计算合计
        double taxAmount = materialLists.stream ().mapToDouble ( detail -> Double.parseDouble ( StringUtils.isBlank ( detail.getTaxAmount () ) ? "0" : detail.getTaxAmount () ) ).sum ();
        double moneyAmount = materialLists.stream ().mapToDouble ( detail -> Double.parseDouble ( StringUtils.isBlank ( detail.getAmountMoney () ) ? "0" : detail.getAmountMoney () ) ).sum ();
        double totalTaxPrice = materialLists.stream ().mapToDouble ( detail -> Double.parseDouble ( StringUtils.isBlank ( detail.getTotalTaxPrice () ) ? "0" : detail.getTotalTaxPrice () ) ).sum ();
        double taxAmountBase = materialLists.stream().mapToDouble(detail -> Double.parseDouble(StringUtils.isBlank(detail.getTaxAmountBase()) ? "0" : detail.getTaxAmountBase())).sum();
        double totalTaxPriceBase = materialLists.stream().mapToDouble(detail -> Double.parseDouble(StringUtils.isBlank(detail.getTotalTaxPriceBase()) ? "0" : detail.getTotalTaxPriceBase())).sum();
        double amountMoneyBase = materialLists.stream().mapToDouble(detail -> Double.parseDouble(StringUtils.isBlank(detail.getAmountMoneyBase()) ? "0" : detail.getAmountMoneyBase())).sum();
        kingProcureRefund.setTaxAmount ( String.valueOf ( taxAmount ) );
        kingProcureRefund.setMoneyAmount ( String.valueOf ( moneyAmount ) );
        kingProcureRefund.setTotalPriceTax ( String.valueOf ( totalTaxPrice ) );
        kingProcureRefund.setTaxAmountBase(String.valueOf(taxAmountBase));
        kingProcureRefund.setTotalPriceTaxBase(String.valueOf(totalTaxPriceBase));
        kingProcureRefund.setMoneyAmountBase(String.valueOf(amountMoneyBase));
        boolean updated = this.updateById(kingProcureRefund);
        if ( !updated ) {
            return AjaxResult.error( "修改失败!" );
        }
        return AjaxResult.success ( "修改成功!",kingProcureRefund.getId());
    }

    /**
     * 采购退料单审核完毕后调用此方法更新即时库存
     * @param procureRefundMaterialLists 采购退料单物料明细
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRealTimeInventory(List<KingProcureRefundMaterialEntity> procureRefundMaterialLists) {
        if(CollectionUtils.isEmpty(procureRefundMaterialLists)){
            throw new RuntimeException("采购退料单物料明细为空,更新即时库存失败！");
        }
        procureRefundMaterialLists.forEach(refundMaterial -> {
            //采购退料单数量
           String refundNum = refundMaterial.getRefundNum();
           //查询即时库存
            KingRealInventoryQueryDto realInventoryQueryDto = new KingRealInventoryQueryDto();
            realInventoryQueryDto.setMaterialCode(refundMaterial.getMaterialCode());
            realInventoryQueryDto.setWarehouseCode(refundMaterial.getWarehouseCode());
            KingRealInventoryEntity realInventory = kingRealInventoryService.getRealInventoryByMaterialAndWarehouseAndPosition(realInventoryQueryDto);
            if(Objects.isNull(realInventory)){
                throw new RuntimeException("库存无此数据,更新即时库存失败!");
            }
            String inventoryNum = realInventory.getInventoryNum();
            if(new BigDecimal(inventoryNum).compareTo(new BigDecimal(refundNum)) < 0){
                throw new RuntimeException("库存数量不足,采购退料失败!");
            }
            String surplusInventoryNum = CommonUtil.subStr(inventoryNum, refundNum, 2);
            KingRealInventoryEntity updateRealInventory = new KingRealInventoryEntity();
            updateRealInventory.setId(realInventory.getId());
            updateRealInventory.setInventoryNum(surplusInventoryNum);
            updateRealInventory.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
            updateRealInventory.setUpdateTime(DateUtils.getNowDate());
            kingRealInventoryService.updateKingRealInventoryEntity(updateRealInventory);
        });
    }



    /**
     * 采购入库单下推采购退料单
     * 采购退料单物料明细数量检查
     * 1.查询该采购入库单该物料已经退料的数量；
     * 2.此次退料数量不能超过采购退料单总计数量；
     * @param procureRefundMaterial
     */
    private KingProcureRefundMaterialEntity checkMaterialNumByInventory(KingProcureRefundMaterialEntity procureRefundMaterial){
        if(Objects.nonNull(procureRefundMaterial.getSourceMaterialDetailId())){
            //获取源单采购入库单该物料明细的入库总数量
            KingInventoryMaterialEntity inventoryMaterial = kingInventoryMaterialService.getById(procureRefundMaterial.getSourceMaterialDetailId());
            //判断业务日期是否在源单日期之后
            KingInventoryEntity kingInventory = kingInventoryService.getById(inventoryMaterial.getInventoryId());
            if(Objects.nonNull(kingInventory)){
                LocalDate currentDate = LocalDate.now();
                LocalDate inventoryLocalDate = kingInventory.getInventoryTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                if (!currentDate.isAfter(inventoryLocalDate) && currentDate.isEqual(inventoryLocalDate)) {
                    throw new CustomException("采购退料单时间不能早于采购入库单时间！");
                }
            }
            double inventoryNum = inventoryMaterial.getReceiptsNum() != null ? Double.parseDouble(inventoryMaterial.getReceiptsNum()) : 0;
            //查询该物料是否有已经退料的数量
            List<KingProcureRefundMaterialEntity> procureRefundMaterials = kingProcureRefundMaterialService.list(new LambdaQueryWrapper<KingProcureRefundMaterialEntity>().eq(KingProcureRefundMaterialEntity::getSourceInventoryId, procureRefundMaterial.getSourceInventoryId())
                .eq(KingProcureRefundMaterialEntity::getSourceMaterialDetailId, procureRefundMaterial.getSourceMaterialDetailId()));
            double numByOut = 0;
            if(!CollectionUtils.isEmpty(procureRefundMaterials)){
                numByOut = procureRefundMaterials.stream ().mapToDouble (p -> Double.parseDouble(p.getRefundNum()) ).sum ();
            }
            //判断此次退料数量是否大于剩余可退料数量
            double surplusNum = inventoryNum - numByOut;
            if(Double.parseDouble(procureRefundMaterial.getRefundNum()) > surplusNum){
                throw new CustomException("退料数量不可超过采购入库单数量！");
            }
            //平账
            if(Double.parseDouble(procureRefundMaterial.getRefundNum()) == surplusNum){
                //采购入库单该物料明细的价税合计
                KingInventoryMaterialDetailEntity kingInventoryMaterialDetail = kingInventoryMaterialDetailService.getOne(new LambdaQueryWrapper<KingInventoryMaterialDetailEntity>().eq(KingInventoryMaterialDetailEntity::getInventoryMaterialId, inventoryMaterial.getId()));
                String inventoryTotalTaxPrice = kingInventoryMaterialDetail.getTotalTaxPrice();
                //该物料明细已经形成采购退料单的价税合计
                List<String> procureRefundMaterialIdList = procureRefundMaterials.stream().filter(Objects::nonNull).distinct().map(KingProcureRefundMaterialEntity::getId).collect(Collectors.toList());
                List<KingProcureRefundMaterialDetailEntity> procureRefundMaterialDetailList = kingProcureRefundMaterialDetailService.list(new LambdaQueryWrapper<KingProcureRefundMaterialDetailEntity>().in(KingProcureRefundMaterialDetailEntity::getProcureRefundMaterialId, procureRefundMaterialIdList));
                BigDecimal procureRefundMaterialDetailTotalTaxPrice = procureRefundMaterialDetailList.stream().filter(Objects::nonNull).map(materialDetail -> new BigDecimal(materialDetail.getTotalTaxPrice())).reduce(BigDecimal.ZERO, BigDecimal::add);
                //计算剩余的价税合计(该物料明细的价税合计 ➖ 已经形成采购入库单的价税合计)
                BigDecimal surplusTotalTaxPrice = new BigDecimal(inventoryTotalTaxPrice).subtract(procureRefundMaterialDetailTotalTaxPrice);
                //计算单价(剩余的价税合计 / 此次数量)
                BigDecimal price = surplusTotalTaxPrice.divide(new BigDecimal(procureRefundMaterial.getRefundNum()), BigDecimal.ROUND_HALF_UP);
                //将值赋值给原字段
                procureRefundMaterial.getMaterialDetail().setPrice(String.valueOf(price));
                procureRefundMaterial.getMaterialDetail().setTotalTaxPrice(String.valueOf(surplusTotalTaxPrice));
            }
        }
        return procureRefundMaterial;
    }

    /**
     * 收料通知单下推采购退料单
     * 1.根据源单id和源单物料明细id查询收料通知单检验不良的数量
     * 2.查询已经下推形成采购退料单的数量
     * @param procureRefundMaterial
     * @return
     */
    private KingProcureRefundMaterialEntity checkMaterialNumByReceiveNotice(KingProcureRefundMaterialEntity procureRefundMaterial){
        if(Objects.nonNull(procureRefundMaterial.getSourceMaterialDetailId())){
            //查询源单物料明细判断的总数
            List<KingCheckMaterialUseDecisionEntity> decisionList = queryCheckMaterialByReceiveNotice(procureRefundMaterial.getSourceInventoryId(), procureRefundMaterial.getSourceMaterialDetailId());
            double sumNum = 0;
            if(!CollectionUtils.isEmpty(decisionList)){
                sumNum = decisionList.stream().mapToDouble(materialDecision -> Double.parseDouble(materialDecision.getNum())).sum();
            }
            //查询已经下推退料单的数量
            List<KingProcureRefundMaterialEntity> procureRefundMaterials = kingProcureRefundMaterialService.list(new LambdaQueryWrapper<KingProcureRefundMaterialEntity>().eq(KingProcureRefundMaterialEntity::getSourceInventoryId, procureRefundMaterial.getSourceInventoryId()).eq(KingProcureRefundMaterialEntity::getSourceMaterialDetailId, procureRefundMaterial.getSourceMaterialDetailId()));
            double numByOut = 0;
            if(!CollectionUtils.isEmpty(procureRefundMaterials)){
                numByOut = procureRefundMaterials.stream ().mapToDouble (p -> Double.parseDouble(p.getRefundNum()) ).sum ();
            }
            //剩余可下推数量
            double surplusNum = sumNum - numByOut;
            if(Double.parseDouble(procureRefundMaterial.getRefundNum()) > surplusNum){
                throw new CustomException("退料数量不可超过收料通知单可下推数量！");
            }
        }
        return procureRefundMaterial;
    }


    /**
     * 根据收料通知单id和物料明细id查询检验单判断数量
     * 目前只统计了检验单判断的数量，未包含让步接收的数量(让步接收的也可以下推不良品)
     * @param receiveNoticeId
     * @param materialId
     * @return
     */
    private List<KingCheckMaterialUseDecisionEntity> queryCheckMaterialByReceiveNotice(String receiveNoticeId,String materialId){
        return checkMaterialUseDecisionService.list(
            new LambdaQueryWrapper<KingCheckMaterialUseDecisionEntity>().eq(KingCheckMaterialUseDecisionEntity::getRelationId, receiveNoticeId)
                .eq(KingCheckMaterialUseDecisionEntity::getSourceMaterialDetailId, materialId)
                .and(wrapper -> wrapper.in(KingCheckMaterialUseDecisionEntity::getUseDecision, ConstUtil.CHECK_DECISION_REJECT)));
    }


    /**
     * 保存采购退料单物料明细以及物料其他信息
     * @param kingProcureRefund
     * @param materialLists
     */
    private void saveMaterialAndDetail(KingProcureRefundEntity kingProcureRefund,List<KingProcureRefundMaterialEntity> materialLists){
        for(KingProcureRefundMaterialEntity material : materialLists){
            String materialId = SnowflakeIdWorker.getInstance().nextStringId();
            material.setId(materialId);
            material.setRelationId(kingProcureRefund.getId());
            material.setCreateBy(kingProcureRefund.getCreateName());
            material.setCreateTime(kingProcureRefund.getCreateTime());
            material.setSourceType(kingProcureRefund.getSourceType());
            boolean materialFlag = kingProcureRefundMaterialService.save(material);
            if(!materialFlag){
                throw new RuntimeException("新增采购退料单物料明细失败！");
            }
            KingProcureRefundMaterialDetailEntity kingProcureRefundMaterialDetail = material.getMaterialDetail();
            Optional.ofNullable(kingProcureRefundMaterialDetail).ifPresent(materialDetail -> {
                String materialDetailId = SnowflakeIdWorker.getInstance().nextStringId();
                materialDetail.setId(materialDetailId);
                materialDetail.setProcureRefundId(kingProcureRefund.getId());
                materialDetail.setProcureRefundMaterialId(materialId);
                materialDetail.setCreateBy(material.getCreateBy());
                materialDetail.setCreateTime(material.getCreateTime());
                boolean materialDetailFlag = kingProcureRefundMaterialDetailService.save(materialDetail);
                if(materialDetailFlag){
                    throw new RuntimeException("新增采购退料单物料分录信息失败！");
                }
                if(!CollectionUtils.isEmpty(materialDetail.getMaterialDetailSerials())){
                    List<KingProcureRefundMaterialDetailSerialEntity> materialDetailSerials = materialDetail.getMaterialDetailSerials();
                    for(KingProcureRefundMaterialDetailSerialEntity materialDetailSerial : materialDetailSerials){
                        materialDetailSerial.setId(SnowflakeIdWorker.getInstance().nextStringId());
                        materialDetailSerial.setProcureRefundId(kingProcureRefund.getId());
                        materialDetailSerial.setProcureRefundMaterialId(materialId);
                        materialDetailSerial.setMaterialDetailId(materialDetailId);
                        materialDetailSerial.setCreateBy(material.getCreateBy());
                        materialDetailSerial.setCreateTime(material.getCreateTime());
                        kingProcureRefundMaterialDetailSerialService.save(materialDetailSerial);
                    }
                }
            });
        }
    }

    /**
     * 查询金蝶-采购退料单
     *
     * @param id 金蝶-采购退料单ID
     * @return 金蝶-采购退料单
     */
    @Override
    public KingProcureRefundEntity selectKingProcureRefundEntityById(String id)
    {
        KingProcureRefundEntity kingProcureRefundEntity = kingProcureRefundMapper.selectKingProcureRefundEntityById(id);
        Optional.ofNullable(kingProcureRefundEntity).ifPresent(kingProcureRefund -> {
            //退料组织
            SysDept refundOrg = sysDeptService.getOne(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptCode,kingProcureRefund.getRefundOrg()));
            Optional.ofNullable(refundOrg).ifPresent(r -> {
                kingProcureRefund.setRefundOrgName(r.getDeptName());
            });
            //需求组织
            SysDept requireOrg = sysDeptService.getOne(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptCode, kingProcureRefund.getRequireOrg()));
            Optional.ofNullable(requireOrg).ifPresent(r -> {
                kingProcureRefund.setRequireOrgName(r.getDeptName());
            });
            //采购组织
            SysDept purchaseOrg = sysDeptService.getOne(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptCode,kingProcureRefund.getPurchaseOrg()));
            Optional.ofNullable(purchaseOrg).ifPresent(r -> {
                kingProcureRefund.setPurchaseOrgName(r.getDeptName());
            });
            //采购部门
            SysDept purchaseDept = sysDeptService.getOne(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptCode,kingProcureRefund.getPurchaseDept()));
            Optional.ofNullable(purchaseDept).ifPresent(r -> {
                kingProcureRefund.setPurchaseDeptName(r.getDeptName());
            });
            //退料部门
            SysDept refundDept = sysDeptService.getOne(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptCode,kingProcureRefund.getRefundDept()));
            Optional.ofNullable(refundDept).ifPresent(r -> {
                kingProcureRefund.setRefundDeptName(r.getDeptName());
            });
            //库存组
            KingBaseBusinessGroupDetailEntity inventoryGroupDetail = kingBaseBusinessGroupDetailService.getOne(new LambdaQueryWrapper<KingBaseBusinessGroupDetailEntity>().eq(KingBaseBusinessGroupDetailEntity::getBusinessCode, kingProcureRefund.getInventoryGroup()));
            Optional.ofNullable(inventoryGroupDetail).ifPresent(b -> {
                kingProcureRefund.setInventoryGroupName(b.getBusinessName());
            });
            //仓管员
            SysUser managementBy = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserCode, kingProcureRefund.getManagementBy()));
            Optional.ofNullable(managementBy).ifPresent(m -> {
                kingProcureRefund.setManagementByName(m.getUserName());
            });
            //采购组
            KingBaseBusinessGroupDetailEntity purchaseGroupDetail = kingBaseBusinessGroupDetailService.getOne(new LambdaQueryWrapper<KingBaseBusinessGroupDetailEntity>().eq(KingBaseBusinessGroupDetailEntity::getBusinessCode, kingProcureRefund.getPurchaseGroup()));
            Optional.ofNullable(purchaseGroupDetail).ifPresent(b -> {
                kingProcureRefund.setPurchaseGroupName(b.getBusinessName());
            });
            //采购员
            SysUser purchaseBy = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserCode, kingProcureRefund.getPurchaseBy()));
            Optional.ofNullable(purchaseBy).ifPresent(p -> {
                kingProcureRefund.setPurchaseByName(p.getUserName());
            });
            //供应商
            SupplierEntity supplierEntity = supplierService.getById(kingProcureRefund.getSupplierId());
            Optional.ofNullable(supplierEntity).ifPresent(p -> {
                kingProcureRefund.setSupplierName(p.getSupplierName());
            });
            //接收方
            SupplierEntity providerName = supplierService.getById(kingProcureRefund.getProviderId());
            Optional.ofNullable(providerName).ifPresent(p -> {
                kingProcureRefund.setProviderName(p.getSupplierName());
            });
            //接收方联系人
            KingBaseContactsEntity baseContactsEntity = baseContactsService.getOne(new LambdaQueryWrapper<KingBaseContactsEntity>().eq(KingBaseContactsEntity::getContactsCode, kingProcureRefund.getProviderContacts()));
            Optional.ofNullable(baseContactsEntity).ifPresent(b -> {
                kingProcureRefund.setProviderContactsName(b.getName());
            });
            //结算方名称
            SupplierEntity balanceName = supplierService.getById(kingProcureRefund.getBalanceId());
            Optional.ofNullable(balanceName).ifPresent(b -> {
                kingProcureRefund.setBalanceName(b.getSupplierName());
            });
            //收款方名称
            SupplierEntity receiveName = supplierService.getById(kingProcureRefund.getReceiveId());
            Optional.ofNullable(receiveName).ifPresent(r -> {
                kingProcureRefund.setReceiveName(r.getSupplierName());
            });
            //结算组织名称
            SysDept settlementOrg = sysDeptService.getById(kingProcureRefund.getSettlementOrg());
            Optional.ofNullable(settlementOrg).ifPresent(s -> {
                kingProcureRefund.setSettlementOrgName(s.getDeptName());
            });
            //结算方式名称
            KingBaseSettlementTypeEntity kingBaseSettlementType = kingBaseSettlementTypeService.getOne(new LambdaQueryWrapper<KingBaseSettlementTypeEntity>().eq(KingBaseSettlementTypeEntity::getBizCode, kingProcureRefund.getSettlementMethod()));
            Optional.ofNullable(kingBaseSettlementType).ifPresent(k -> {
                kingProcureRefund.setSettlementMethodName(k.getTitle());
            });
            //价目表名称
            KingPurchasePriceEntity purchasePriceEntity = kingPurchasePriceService.getOne(new LambdaQueryWrapper<KingPurchasePriceEntity>().eq(KingPurchasePriceEntity::getCode, kingProcureRefund.getPriceInfoCode()));
            Optional.ofNullable(purchasePriceEntity).ifPresent(p -> {
                kingProcureRefund.setPriceInfoName(p.getName());
            });
            //汇率类型
            if(StringUtils.isNotEmpty(kingProcureRefund.getExchangeRateType())){
                KingBaseExchangeRateTypeEntity exchangeRateType = kingBaseExchangeRateTypeService.getOne(new LambdaQueryWrapper<KingBaseExchangeRateTypeEntity>().eq(KingBaseExchangeRateTypeEntity::getCode, kingProcureRefund.getExchangeRateType()));
                Optional.ofNullable(exchangeRateType).ifPresent(e -> {
                    kingProcureRefund.setExchangeRateTypeName(e.getName());
                });
            }
            //结算币别
            KingBaseCurrencyEntity KingBaseCurrency = kingBaseCurrencyService.getOne(new LambdaQueryWrapper<KingBaseCurrencyEntity>().eq(KingBaseCurrencyEntity::getCode, kingProcureRefund.getSettlementCurrency()));
            Optional.ofNullable(KingBaseCurrency).ifPresent(k -> {
                kingProcureRefund.setSettlementCurrencyName(k.getCurrencyName());
            });
            //折扣表名称
            KingPurchasePriceEntity discountInfo = kingPurchasePriceService.getOne(new LambdaQueryWrapper<KingPurchasePriceEntity>().eq(KingPurchasePriceEntity::getCode, kingProcureRefund.getDiscountInfoCode()));
            Optional.ofNullable(discountInfo).ifPresent(d -> {
                kingProcureRefund.setDiscountInfoName(d.getName());
            });
            //付款条件名称
            KingBaseReceiptPayConditionEntity receiptPayCondition = kingBaseReceiptPayConditionService.getOne(new LambdaQueryWrapper<KingBaseReceiptPayConditionEntity>().eq(KingBaseReceiptPayConditionEntity::getConditionCode, kingProcureRefund.getTermOfPayment()));
            Optional.ofNullable(receiptPayCondition).ifPresent(r -> {
                kingProcureRefund.setTermOfPaymentName(r.getTitle());
            });
            List<KingProcureRefundMaterialEntity> refundMaterials = kingProcureRefundMaterialService.list(new LambdaQueryWrapper<KingProcureRefundMaterialEntity>().eq(KingProcureRefundMaterialEntity::getRelationId, kingProcureRefund.getId()));
            refundMaterials.stream().filter(Objects::nonNull).forEach(material -> {
                //库存状态名称
                if(StringUtils.isNotEmpty(material.getInventoryStatus())){
                    KingBaseInventoryStatusEntity inventoryStatus = kingBaseInventoryStatusService.getOne(new LambdaQueryWrapper<KingBaseInventoryStatusEntity>().eq(KingBaseInventoryStatusEntity::getInventoryStatusCode, material.getInventoryStatus()));
                    Optional.ofNullable(inventoryStatus).ifPresent(i -> {
                        material.setInventoryStatusName(i.getInventoryStatusName());
                    });
                }
                //库存单位
                if(StringUtils.isNotEmpty(material.getInventoryUnit())){
                    KingBaseMeteringUnitEntity inventoryUnit = meteringUnitService.getOne(new LambdaQueryWrapper<KingBaseMeteringUnitEntity>().eq(KingBaseMeteringUnitEntity::getMeteringUnitCode, material.getInventoryUnit()));
                    Optional.ofNullable(inventoryUnit).ifPresent(i -> {
                        material.setInventoryUnitName(i.getMeteringUnitName());
                    });
                }
                //计价单位
                if(StringUtils.isNotEmpty(material.getPricingUnit())){
                    KingBaseMeteringUnitEntity pricingUnit = meteringUnitService.getOne(new LambdaQueryWrapper<KingBaseMeteringUnitEntity>().eq(KingBaseMeteringUnitEntity::getMeteringUnitCode, material.getPricingUnit()));
                    Optional.ofNullable(pricingUnit).ifPresent(p -> {
                        material.setPricingUnitName(p.getMeteringUnitName());
                    });
                }
                //仓库名称
                if(StringUtils.isNotEmpty(material.getWarehouseCode())){
                    WarehouseEntity warehouseEntity = warehouseService.getOne(new LambdaQueryWrapper<WarehouseEntity>().eq(WarehouseEntity::getWareCode, material.getWarehouseCode()));
                    Optional.ofNullable(warehouseEntity).ifPresent(w -> {
                        material.setWarehouseName(w.getWareName());
                    });
                }
                //采购单位
                if(StringUtils.isNotEmpty(material.getPurchaseUnit())){
                    KingBaseMeteringUnitEntity purchaseUnit = meteringUnitService.getOne(new LambdaQueryWrapper<KingBaseMeteringUnitEntity>().eq(KingBaseMeteringUnitEntity::getMeteringUnitCode, material.getPurchaseUnit()));
                    Optional.ofNullable(purchaseUnit).ifPresent(p -> {
                        material.setPurchaseUnitName(p.getMeteringUnitName());
                    });
                }
                KingProcureRefundMaterialDetailEntity kingProcureRefundMaterialDetail = kingProcureRefundMaterialDetailService.getOne(new LambdaQueryWrapper<KingProcureRefundMaterialDetailEntity>().eq(KingProcureRefundMaterialDetailEntity::getProcureRefundId, kingProcureRefund.getId()).eq(KingProcureRefundMaterialDetailEntity::getProcureRefundMaterialId, material.getId()));
                Optional.ofNullable(kingProcureRefundMaterialDetail).ifPresent(materialDetail -> {
                    List<KingProcureRefundMaterialDetailSerialEntity> materialDetailSerials = kingProcureRefundMaterialDetailSerialService.list(new LambdaQueryWrapper<KingProcureRefundMaterialDetailSerialEntity>()
                    .eq(KingProcureRefundMaterialDetailSerialEntity::getProcureRefundId, kingProcureRefund.getId()).eq(KingProcureRefundMaterialDetailSerialEntity::getProcureRefundMaterialId, material.getId()).eq(KingProcureRefundMaterialDetailSerialEntity::getMaterialDetailId, materialDetail.getId()));
                    materialDetail.setMaterialDetailSerials(materialDetailSerials);
                });
                material.setMaterialDetail(kingProcureRefundMaterialDetail);
            });
            kingProcureRefund.setMaterialLists(refundMaterials);
        });
        return kingProcureRefundEntity;
    }

    /**
     * 查询金蝶-采购退料单列表
     *
     * @param kingProcureRefundEntity 金蝶-采购退料单
     * @return 金蝶-采购退料单
     */
    @Override
    public List<KingProcureRefundEntity> selectKingProcureRefundEntityList(KingProcureRefundEntity kingProcureRefundEntity)
    {
        return kingProcureRefundMapper.selectKingProcureRefundEntityList(kingProcureRefundEntity);
    }

    /**
     * 新增金蝶-采购退料单
     *
     * @param kingProcureRefundEntity 金蝶-采购退料单
     * @return 结果
     */
    @Override
    public int insertKingProcureRefundEntity(KingProcureRefundEntity kingProcureRefundEntity)
    {
        kingProcureRefundEntity.setCreateTime(DateUtils.getNowDate());
        return kingProcureRefundMapper.insertKingProcureRefundEntity(kingProcureRefundEntity);
    }

    /**
     * 修改金蝶-采购退料单
     * @param kingProcureRefundEntity 金蝶-采购退料单
     * @return 结果
     */
    @Override
    public int updateKingProcureRefundEntity(KingProcureRefundEntity kingProcureRefundEntity)
    {
        kingProcureRefundEntity.setUpdateTime(DateUtils.getNowDate());
        return kingProcureRefundMapper.updateKingProcureRefundEntity(kingProcureRefundEntity);
    }

    private void removeMaterialAndDetail(String id){
        kingProcureRefundMaterialService.remove(new LambdaQueryWrapper<KingProcureRefundMaterialEntity>().eq(KingProcureRefundMaterialEntity::getRelationId,id));
        kingProcureRefundMaterialDetailService.remove(new LambdaQueryWrapper<KingProcureRefundMaterialDetailEntity>().eq(KingProcureRefundMaterialDetailEntity::getProcureRefundId,id));
        kingProcureRefundMaterialDetailSerialService.remove(new LambdaQueryWrapper<KingProcureRefundMaterialDetailSerialEntity>().eq(KingProcureRefundMaterialDetailSerialEntity::getProcureRefundId,id));
    }

    /**
     * 批量删除金蝶-采购退料单
     * @param ids 需要删除的金蝶-采购退料单ID
     * @return 结果
     */
    @Override
    public int deleteKingProcureRefundEntityByIds(String[] ids)
    {
        for(String id : ids){
            removeMaterialAndDetail(id);
        }
        return kingProcureRefundMapper.deleteKingProcureRefundEntityByIds(ids);
    }

    /**
     * 删除金蝶-采购退料单信息
     * @param id 金蝶-采购退料单ID
     * @return 结果
     */
    @Override
    public int deleteKingProcureRefundEntityById(String id)
    {
        removeMaterialAndDetail(id);
        return kingProcureRefundMapper.deleteKingProcureRefundEntityById(id);
    }

    @Override
    public AjaxResult getKingProcureRefundSelect(KingProcureRefundSelectQueryDto queryDto) {
        queryDto.setPage(queryDto.getPage() - 1);
        List<KingProcureRefundSelectVo> list = kingProcureRefundMapper.getKingProcureRefundSelect(queryDto);
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(procureRefundVo -> {
                KingProcureRefundMaterialQueryDto materialQueryDto = new KingProcureRefundMaterialQueryDto();
                materialQueryDto.setProcureRefundId(procureRefundVo.getId());
                materialQueryDto.setMaterialDetailId(procureRefundVo.getMaterialDetailId());
                OrderSumResult totalPayableResult = kingInvoicePayableDetailService.getNumAndTotalTaxPriceByProcureRefund(materialQueryDto);
                procureRefundVo.setTotalPayableNum(totalPayableResult.getTotalNum());
                String surplusPayableNum = CommonUtil.sumStr(procureRefundVo.getRefundNum(), totalPayableResult.getTotalNum(), 2);
                procureRefundVo.setSurplusPayableNum(surplusPayableNum);
            });
        }
        Integer totalCount = kingProcureRefundMapper.queryTotalCount(queryDto);
        PageParam records = new PageParam ();
        records.setRecords ( list ).setTotal ( totalCount );
        return AjaxResult.success ( records );
    }

}
